package com.duolaibei.business.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.duolaibei.business.R;
import com.duolaibei.business.api.ApiName;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.config.DIR;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.http.HttpUtils;
import com.duolaibei.business.model.ResponseResult;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.GsonUtil;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.SysUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.view.dialog.PhotoChooseDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xlm on 2017/11/9 0009
 */

public class PerfectDataActivity extends BaseActivity {

    @Inject(R.id.back)
    private RelativeLayout mLayoutBack;
    @Inject(R.id.title)
    private TextView mViewTitle;

    @Inject(R.id.real_name)
    private EditText mEditTextRealName;//真实名称
    @Inject(R.id.simple_name)
    private EditText mEditTextSimpleName;//商户简称
    @Inject(R.id.card_num)
    private EditText mEditTextCardNum;//身份证号码
    @Inject(R.id.card_address)
    private EditText mEditTextDetailAddress;//详细地址

    @Inject(R.id.card_z_image)
    private ImageView mImageViewZ;
    @Inject(R.id.card_f_image)
    private ImageView mImageViewF;
    @Inject(R.id.licence_image)
    private ImageView mImageViewLicence;
    @Inject(R.id.origin_image)
    private ImageView mImageViewOrigin;

    @Inject(R.id.card_z_btn)
    private TextView mTextViewZ;
    @Inject(R.id.card_f_btn)
    private TextView mTextViewF;
    @Inject(R.id.licence_btn)
    private TextView mTextViewLicence;
    @Inject(R.id.origin_btn)
    private TextView mTextViewOrigin;

    @Inject(R.id.licence_name)
    private EditText mEditTextLicenceName;//营业执照号码
    @Inject(R.id.bankcard_num)
    private EditText mEditTextBankcardNum;//银行卡号
    @Inject(R.id.open_bank_name)
    private EditText mEditTextOpenbankName;//开户姓名
    @Inject(R.id.open_bank_address)
    private EditText mEditTextOpenbankAddress;//开户支行
    @Inject(R.id.open_bank_mobile)
    private EditText mEditTextOpenbankMobile;//手机号码

    @Inject(R.id.confirm_data)
    private TextView mEditTextConfirm;//确认信息

    private String type_4;//四种照片类型(card_z card_f licence orgin)
    private String type_2;//拍照或相册(choose take)

    private String card_z;//正面id
    private String card_f;//反面id
    private String licence;//营业执照id
    private String orgin;//组织机构id

    private static final int PERMISSON_CAMER = 1;
    private final static int PHOTO_1 = 1;
    private final static int PHOTO_2 = 2;
    private final static int PHOTO_3 = 3;
    private final static int PHOTO_4 = 4;
    private String photo_1;//正面
    private String photo_2;//反面
    private String photo_3;//营业执照
    private String photo_4;//组织机构

    String path = DIR.TEMP_CAMERA;
    private final static int CAMERA_1 = 5;
    private final static int CAMERA_2 = 6;
    private final static int CAMERA_3 = 7;
    private final static int CAMERA_4 = 8;
    String photoPath;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_perfect_data);
    }

    @Override
    protected void initViews() {
        mViewTitle.setText("完善信息");
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {

    }

    @Override
    protected void onSetListener() {
        mLayoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mImageViewZ.setOnClickListener(this);
        mImageViewF.setOnClickListener(this);
        mImageViewLicence.setOnClickListener(this);
        mImageViewOrigin.setOnClickListener(this);

        mTextViewZ.setOnClickListener(this);
        mTextViewF.setOnClickListener(this);
        mTextViewLicence.setOnClickListener(this);
        mTextViewOrigin.setOnClickListener(this);

        mEditTextConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.card_z_image://正面
            case R.id.card_z_btn:
                type_4 = "card_z";
                showPhotoChooseDialog();
                break;
            case R.id.card_f_image://反面
            case R.id.card_f_btn:
                type_4 = "card_f";
                showPhotoChooseDialog();
                break;
            case R.id.licence_image://营业执照
            case R.id.licence_btn:
                type_4 = "licence";
                showPhotoChooseDialog();
                break;
            case R.id.origin_image://组织机构
            case R.id.origin_btn:
                type_4 = "origin";
                showPhotoChooseDialog();
                break;
            case R.id.confirm_data:
                confirmData();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //相册
                case PHOTO_1:
                    photo_1 = SysUtil.getRealpathFromUri(this, data.getData());
                    Glide.with(this).load(photo_1).into(mImageViewZ);
                    CommonUtil.getimage(photo_1);
                    upPhoto(photo_1);
                    break;
                case PHOTO_2:
                    photo_2 = SysUtil.getRealpathFromUri(this, data.getData());
                    Glide.with(this).load(photo_2).into(mImageViewF);
                    CommonUtil.getimage(photo_2);
                    upPhoto(photo_2);
                    break;
                case PHOTO_3:
                    photo_3 = SysUtil.getRealpathFromUri(this, data.getData());
                    Glide.with(this).load(photo_3).into(mImageViewLicence);
                    CommonUtil.getimage(photo_3);
                    upPhoto(photo_3);
                    break;
                case PHOTO_4:
                    photo_4 = SysUtil.getRealpathFromUri(this, data.getData());
                    Glide.with(this).load(photo_4).into(mImageViewOrigin);
                    CommonUtil.getimage(photo_4);
                    upPhoto(photo_4);
                    break;
                //相机
                case CAMERA_1:
                    photo_1 = photoPath;
                    Glide.with(this).load(photo_1).into(mImageViewZ);
                    CommonUtil.getimage(photo_1);
                    upPhoto(photo_1);
                    break;
                case CAMERA_2:
                    photo_2 = photoPath;
                    Glide.with(this).load(photo_2).into(mImageViewF);
                    CommonUtil.getimage(photo_2);
                    upPhoto(photo_2);
                    break;
                case CAMERA_3:
                    photo_3 = photoPath;
                    Glide.with(this).load(photo_3).into(mImageViewLicence);
                    CommonUtil.getimage(photo_3);
                    upPhoto(photo_3);
                    break;
                case CAMERA_4:
                    photo_4 = photoPath;
                    Glide.with(this).load(photo_4).into(mImageViewOrigin);
                    CommonUtil.getimage(photo_4);
                    upPhoto(photo_4);
                    break;
            }
        }
    }

    /**
     * 上传图片
     */
    private void upPhoto(String photoPath) {
        String loginType = String.valueOf(PreferenceUtil.getParam(Preferences.LOGINTYPE, ""));
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.UPLOAD);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("login_type", loginType);
        if (!"merchant".equals(loginType)) {
            param.add("login_id", String.valueOf(PreferenceUtil.getParam(Preferences.LOGINID, "")));
        }
        param.add("image", new File(photoPath));
        //签名算法
        Map<String, String> map = new HashMap<>();
        map.put("method", ApiName.UPLOAD);
        map.put("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        map.put("login_type", loginType);
        if (!"merchant".equals(loginType)) {
            map.put("login_id", String.valueOf(PreferenceUtil.getParam(Preferences.LOGINID, "")));
        }
        param.add("sign", CommonUtil.toAscIIMd5String(map, true));
        showLoading("图片上传中");
        HttpUtils.getInstance().url(ApiName.API).params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissLoading();
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissLoading();
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToast(result.getInfo());
                    if (result.getStatus() == 1) {
                        try {
                            JSONObject object = new JSONObject(string);
                            JSONObject object1 = object.getJSONObject("data");
                            if ("card_z".equals(type_4)) {
                                card_z = object1.optString("id");
                            } else if ("card_f".equals(type_4)) {
                                card_f = object1.optString("id");
                            } else if ("licence".equals(type_4)) {
                                licence = object1.optString("id");
                            } else if ("origin".equals(type_4)) {
                                orgin = object1.optString("id");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    showToast(string);
                }
            }
        });
    }


    /**
     * 选择照片
     */
    private PhotoChooseDialog mPhotoChooseDialog;

    private void showPhotoChooseDialog() {
        if (mPhotoChooseDialog == null) {
            mPhotoChooseDialog = new PhotoChooseDialog(this);
        }
        mPhotoChooseDialog.setListener(new PhotoChooseDialog.Listener() {
            @Override
            public void onSelectedCamera() {
                type_2 = "take";
                if (checkCameraPermission(PERMISSON_CAMER)) {
                    if ("card_z".equals(type_4)) {
                        take1();
                    } else if ("card_f".equals(type_4)) {
                        take2();
                    } else if ("licence".equals(type_4)) {
                        take3();
                    } else if ("origin".equals(type_4)) {
                        take4();
                    }
                }
            }

            @Override
            public void onSelectedDCIM() {
                type_2 = "choose";
                if (checkCameraPermission(PERMISSON_CAMER)) {
                    if ("card_z".equals(type_4)) {
                        choose1();
                    } else if ("card_f".equals(type_4)) {
                        choose2();
                    } else if ("licence".equals(type_4)) {
                        choose3();
                    } else if ("origin".equals(type_4)) {
                        choose4();
                    }
                }
            }
        });
        mPhotoChooseDialog.show();
    }

    @Override
    public void onCameraPermission(int result_code, boolean result) {
        if (result) {
            if (checkCameraPermission(PERMISSON_CAMER)) {
                if ("choose".equals(type_2)) {
                    if ("card_z".equals(type_4)) {
                        choose1();
                    } else if ("card_f".equals(type_4)) {
                        choose2();
                    } else if ("licence".equals(type_4)) {
                        choose3();
                    } else if ("origin".equals(type_4)) {
                        choose4();
                    }
                } else if ("take".equals(type_2)) {
                    if ("card_z".equals(type_4)) {
                        take1();
                    } else if ("card_f".equals(type_4)) {
                        take2();
                    } else if ("licence".equals(type_4)) {
                        take3();
                    } else if ("origin".equals(type_4)) {
                        take4();
                    }
                }
            }
        } else {
            showToast("拒绝相机功能，您将不能通过相机拍照");
        }
    }

    /**
     * 拍摄正面
     */
    private void take1() {
        photoPath = path + CommonUtil.getCurrentMS() + ".jpg";
        SysUtil.startCamera(this, new File(photoPath), CAMERA_1);
    }

    /**
     * 拍摄反面
     */
    private void take2() {
        photoPath = path + CommonUtil.getCurrentMS() + ".jpg";
        SysUtil.startCamera(this, new File(photoPath), CAMERA_2);
    }

    /**
     * 拍摄营业执照
     */
    private void take3() {
        photoPath = path + CommonUtil.getCurrentMS() + ".jpg";
        SysUtil.startCamera(this, new File(photoPath), CAMERA_3);
    }

    /**
     * 拍摄组织机构代码
     */
    private void take4() {
        photoPath = path + CommonUtil.getCurrentMS() + ".jpg";
        SysUtil.startCamera(this, new File(photoPath), CAMERA_4);
    }


    /**
     * 选择正面
     */
    private void choose1() {
        SysUtil.choosePhoto(this, PHOTO_1);
    }

    /**
     * 选择反面
     */
    private void choose2() {
        SysUtil.choosePhoto(this, PHOTO_2);
    }

    /**
     * 选择营业执照
     */
    private void choose3() {
        SysUtil.choosePhoto(this, PHOTO_3);
    }

    /**
     * 选择组织机构代码
     */
    private void choose4() {
        SysUtil.choosePhoto(this, PHOTO_4);
    }


    /**
     * 提交认证信息
     */
    private void confirmData() {
        String realName = mEditTextRealName.getText().toString();
        String simpleName = mEditTextSimpleName.getText().toString();
        String cardNum = mEditTextCardNum.getText().toString();
        String detailAddress = mEditTextDetailAddress.getText().toString();

        String licenceName = mEditTextLicenceName.getText().toString();
        String bankcardNum = mEditTextBankcardNum.getText().toString();
        String openbankName = mEditTextOpenbankName.getText().toString();
        String openbankAddress = mEditTextOpenbankAddress.getText().toString();
        String openbankMobile = mEditTextOpenbankMobile.getText().toString();
        if (CommonUtil.isEmpty(realName)) {
            showToast("请输入真实名称/商户姓名");
            return;
        }
        if (CommonUtil.isEmpty(simpleName)) {
            showToast("请输入商户简称");
            return;
        }
        if (CommonUtil.isEmpty(cardNum)) {
            showToast("请输入身份证号码");
            return;
        }
        if (CommonUtil.isEmpty(detailAddress)) {
            showToast("请输入详细地址");
            return;
        }
        // ---------------图片-------begin----//
        if (CommonUtil.isEmpty(card_z)) {
            showToast("请上传身份证正面");
            return;
        }
        if (CommonUtil.isEmpty(card_f)) {
            showToast("请上传身份证反面");
            return;
        }
        if (CommonUtil.isEmpty(licence)) {
            showToast("请上传营业执照");
            return;
        }
        if (CommonUtil.isEmpty(orgin)) {
            showToast("请上传组织机构照");
            return;
        }
        // ---------------图片-------end------//
        if (CommonUtil.isEmpty(licenceName)) {
            showToast("请输入营业执照号码");
            return;
        }
        if (CommonUtil.isEmpty(bankcardNum)) {
            showToast("请输入银行卡号");
            return;
        }
        if (CommonUtil.isEmpty(openbankName)) {
            showToast("请输入开户姓名");
            return;
        }
        if (CommonUtil.isEmpty(openbankAddress)) {
            showToast("请输入开户支行");
            return;
        }
        if (CommonUtil.isEmpty(openbankMobile)) {
            showToast("请输入手机号");
            return;
        }

        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.USERCERT);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("login_type", "merchant");

        param.add("real_name", realName);
        param.add("nickname", simpleName);
        param.add("cards_code", cardNum);
        param.add("address", detailAddress);

        param.add("cardsz_img", card_z);
        param.add("cardsf_img", card_f);
        param.add("license_img", licence);
        param.add("org_img", orgin);

        param.add("businessLicense", licenceName);
        param.add("bank_card", bankcardNum);
        param.add("bank_account_name", openbankName);
        param.add("bank_branch_name", openbankAddress);
        param.add("tel", openbankMobile);

        param.add("sign", param.getMd5String());
        showLoading("信息提交中");
        HttpUtils.getInstance().url(ApiName.API).params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissLoading();
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissLoading();
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToast(result.getInfo());
                    if (result.getStatus() == 1) {
                        setResult(RESULT_OK);
                        finish();
                    }
                } else {
                    showToast(string);
                }
            }
        });

    }
}
